package a66weding.com.jiehuntong.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XScrollView;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.activity.home.HomeShopCaseActivity;
import a66weding.com.jiehuntong.activity.home.HomeShopdetailQRActivity;
import a66weding.com.jiehuntong.activity.home.HomeStoreDetailsActivity;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.adapter.FriendListAdapter;
import a66weding.com.jiehuntong.adapter.ShopAdapterStroeDetail;
import a66weding.com.jiehuntong.adapter.ShopAdapterStroeDetail2;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HomeBotomListBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShopDetBean;
import a66weding.com.jiehuntong.beans.StoreDetailGuess;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.fragment.category.bean.ShopDetBean;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.CircleImageView;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.widgets.DividerItemDecoration;
import a66weding.com.jiehuntong.widgets.NoScrollGridView;
import a66weding.com.jiehuntong.widgets.dialog.MyDialog;
import a66weding.com.jiehuntong.widgets.scrollreflash.PullToLoadScroll;
import a66weding.com.jiehuntong.widgets.scrollreflash.PullToLoadScrollLissener;

/**
 * Created by admin on 2016/8/4.
 * 店铺详情
 */
public class ShopDetailsActivity extends BaseHomeActivity implements OnNetResultListener,View.OnClickListener{
    //图片;
    private ImageView shop_pic_imag;
    //logo图片
//    private CircleImageView shop_image_circle;
    private ImageView shop_image_circle;
    //公司名称
    private TextView shop_name;
    //公司地点
    private TextView shop_content;
    //是否已经关注
    private TextView shop_attention_tv;
    //粉丝
    private TextView shop_Fans_num;
    //粉丝数;
    private int NumberOffans = 0;
    //案例数
    private TextView shop_case;
    //全部商品
    private TextView shop_allp;
    //新品数
    private TextView shop_new;
    //返回键
    private LinearLayout lay_back;
    //搜索
    private EditText mSearchEt;
    //初始进度条
    private LinearLayout mProgressLay;
    //是否有数据界面
    private LinearLayout mNoNetLay;
    private boolean isLogin;
    private User user;
    private User.DataBean userBean;
//    private String nvcNo;
    private int memberID;
    private boolean isAttention;
    private String getNvcNo = "";
    private PopupWindow mPopWindow;
    private MeShopDetBean meShopDetBean;
    private int BusinessID;
    private ViewGroup mContentLay;
    private XRefreshView xRefreshView;//上啦刷新列表
    //适配器
    private boolean  isDownRefresh = true;
    private ShopAdapterStroeDetail2 adapter;
    //gridview 适配器
    private NoScrollGridView shopDettails_gridview;
    //全部商品
    private LinearLayout lay_shopdetail_all;
    //案例商品
    private  LinearLayout lay_shopdetail_case;
    //新上架的商品
    private LinearLayout lay_shopdetail_new;
    private final int REQUEST_LOGIN_CODE=4444;
    //电话
    private ImageView shop_pw;
    private ImageView   mBackIv ;
    private  final int  DIALOG=1;
    private final int REFLASH = 2;
    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;
    private boolean isCanClick=true;
    private int imgWidth= DensityUtil.dip2px(30);
    private int imgHeight=DensityUtil.dip2px(30);
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DIALOG:
                    if(myDialog!=null) {
                        myDialog.dismiss();
                    }
                    break;
                case  REFLASH:
                    refreshView_xScrollview.scrollTo(0,0);
                    break;
            }
        }
    };
    private XScrollView refreshView_xScrollview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail1);
        Intent intent = getIntent();
        if(intent!=null) {
            getNvcNo = intent.getStringExtra("nvc_num");
            BusinessID = getIntent().getIntExtra("BusinessID",0);
        }

        isLogin  = ((GlobalApplication)getApplication()).isLogin();
        if(isLogin) {
            user = DataWareHourse.getInstance().getmUser();
            userBean = user.getData().get(0);
            memberID=userBean.getI_Id();
        }
        initView();
        meInitData();
        //获取网络数据;
        getNetData(1);
    }

    private void initView(){
        mBackIv = (ImageView) findViewById(R.id.cate_search_back);
        //电话
        shop_pw = (ImageView) findViewById(R.id.shop_pw);
        shop_pw.setOnClickListener(this);
        //全部
        lay_shopdetail_all = (LinearLayout) findViewById(R.id.lay_shopdetail_all);
        lay_shopdetail_all.setOnClickListener(this);
        //案例数
        lay_shopdetail_case = (LinearLayout) findViewById(R.id.lay_shopdetail_case);
        lay_shopdetail_case.setOnClickListener(this);
        //新上架的商品数
        lay_shopdetail_new = (LinearLayout) findViewById(R.id.lay_shopdetail_new);
        lay_shopdetail_new.setOnClickListener(this);
        //图片
        shop_pic_imag = (ImageView) findViewById(R.id.shop_pic_imag);
        shop_pic_imag.setOnClickListener(this);
        //logo
//        shop_image_circle = (CircleImageView) findViewById(R.id.shop_image_circle);
        shop_image_circle = (ImageView) findViewById(R.id.shop_image_circle);
        //粉丝数
        shop_Fans_num = (TextView) findViewById(R.id.shop_Fans_num);
        //关注
        shop_attention_tv = (TextView)findViewById(R.id.shop_attention_tv);
        shop_attention_tv.setOnClickListener(this);
        //shop 名字
        shop_name = (TextView) findViewById(R.id.shop_name);
        //全部商品
        shop_allp = (TextView) findViewById(R.id.shop_allp);
        //案例数
        shop_case = (TextView) findViewById(R.id.shop_case);
        //新品数
        shop_new = (TextView)findViewById(R.id.shop_new);
        //内容
        shop_content = (TextView) findViewById(R.id.shop_content);
        //返回键
        lay_back = (LinearLayout) findViewById(R.id.lay_back);
        lay_back.setOnClickListener(this);
        //
        mProgressLay = (LinearLayout) findViewById(R.id.progress);
        mNoNetLay = (LinearLayout) findViewById(R.id.noNetLay);
        mNoNetLay.setOnClickListener(this);
        mSearchEt = (EditText) findViewById(R.id.cate_search);
        initRefreshView();
        //搜索
        mSearchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    // 先隐藏键盘
                    ((InputMethodManager) mSearchEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //跳转activity
                    Intent intent = new Intent();
                    intent.setClass(ShopDetailsActivity.this, CategorySearchActivity.class);
                    String searchStr = mSearchEt.getText().toString();
                    if (searchStr.contains(" ")){
                        Toast.makeText(ShopDetailsActivity.this,"请不要输入空格",Toast.LENGTH_SHORT).show();
                        return false;
                    } else if(!TextUtils.isEmpty(searchStr.trim())) {
                        intent.putExtra("searchinfo",searchStr);
                        intent.putExtra("return","店铺详情");
                        ShopDetailsActivity.this.startActivity(intent);
                        return true;
                    } else {
                        Toast.makeText(ShopDetailsActivity.this,"请输入搜索内容",Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }
                return false;
            }
        });
    }

    /**
     * 初始化上啦刷新
     */
    //页数
    private int page = 1;
    private void initRefreshView() {
        mContentLay = xRefreshView = (XRefreshView)findViewById(R.id.help_xrefreshview);
        shopDettails_gridview = (NoScrollGridView) findViewById(R.id.shopDettails_gridview);
        refreshView_xScrollview = (XScrollView) findViewById(R.id.refreshView_xScrollview);
        //是否允许下拉刷新
        xRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        xRefreshView.setAutoLoadMore(true);
        adapter = new ShopAdapterStroeDetail2(this,null);
        shopDettails_gridview.setAdapter(adapter);
        //设置item点击事件
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isDownRefresh = true;
                getNetData(1);
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isDownRefresh = false;
                ++page;
                getNetData(page);
            }
        });
    }
    /**
     * GET WeddingMobileApi/get_ProductList?Token={Token}&BusinessID={BusinessID}&pageIndex={pageIndex}
     根据商家ID返回改商家所有的已上架商品信息
     * @param pagindex
     */
    public  void  getNetData(int pagindex){
        String url =  RequestCode.get_ProductList+"&BusinessID="+BusinessID+"&pageIndex="+pagindex;
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this, StoreDetailGuess.class,RequestCode.GET_PRODUCTLIST);
        HttpHandleUtil.executeCommonGet(this,bottomListRequestBean);
    }
    private void meInitData(){
        // 发起网络请求
        String url = Url.GET_BUSINESSDETAIL_NO+"&nvcNo="+getNvcNo+"&memberID="+memberID;
        HttpRequestBean RequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this, MeShopDetBean.class,RequestCode.GET_CASESDETAIL);
        HttpHandleUtil.executeCommonGet(this,RequestBean);
    }
    //数据
    private CommonResultBean commonResultBean;
    private MyDialog myDialog;
    //猜你喜欢
    private StoreDetailGuess bean;
    private List<StoreDetailGuess.DataBean> homebtList;
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (isDownRefresh){
            xRefreshView.stopRefresh();
        }else{
            xRefreshView.stopLoadMore();
        }
        refreshViewLay(HAVEDATA, mContentLay, mProgressLay, mNoNetLay);
        if (data instanceof CommonResultBean) {
            commonResultBean = (CommonResultBean) data;
            switch (commonResultBean.getResCode()) {
                case "0000":
                    if (isAttention) {
                        if (meShopDetBean != null) {
                            meShopDetBean.getData().setCollectionStare(true);
                            int businessMemberCount = meShopDetBean.getData().getBusinessMemberCount();
                            meShopDetBean.getData().setBusinessMemberCount(++businessMemberCount);
                            shop_Fans_num.setText("" + (businessMemberCount));
                        }
                        isCanClick=true;
                        shop_attention_tv.setText("已关注");
                        myDialog = new MyDialog(this, "关注成功!");
                        myDialog.show();
                        mHandler.sendEmptyMessageDelayed(DIALOG, 800);
                    } else {

                        if (meShopDetBean != null) {
                            meShopDetBean.getData().setCollectionStare(false);
                            int businessMemberCount = meShopDetBean.getData().getBusinessMemberCount();
                            meShopDetBean.getData().setBusinessMemberCount(--businessMemberCount);
                            shop_Fans_num.setText("" + (businessMemberCount));
                        }
                        isCanClick=true;
                        shop_attention_tv.setText("+ 关注");
                        myDialog = new MyDialog(this, "取消关注成功!");
                        myDialog.show();
                        mHandler.sendEmptyMessageDelayed(DIALOG, 800);
                    }
            }
        }
        if (data instanceof MeShopDetBean) {
            meShopDetBean = (MeShopDetBean) data;
            if ("0000".equals(meShopDetBean.getResCode())) {
                setData();
            }
        }

        if (data instanceof StoreDetailGuess) {
            bean = (StoreDetailGuess) data;
            switch (bean.getResCode()) {
                case "0000":
                    homebtList = bean.getData();
                    if (isDownRefresh){
                        adapter.clear();
                        Message msg = mHandler.obtainMessage();
                        msg.what = 2;
                        mHandler.sendMessage(msg);
                    }
                    adapter.append(homebtList);

                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        switch (errorBean.getErrorCode()) {
            case ErrorBean.TIMEOUT:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            case ErrorBean.NONET:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            default:
                Tools.showDataErrDialogSmall(this,"",true);
        }
    }
    protected void refreshViewLay(int state,View mContentLay,View mProgressLay,View mNonetLay){
        switch (state) {
            case HAVEDATA:
                mProgressLay.setVisibility(View.GONE);
                if(mContentLay.isShown()) {
                    return;
                }else{
                    mContentLay.setVisibility(View.VISIBLE);
                }
                mProgressLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mProgressLay.setVisibility(View.VISIBLE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.GONE);
                break;
            case NONET:
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.VISIBLE);
                break;
        }
    }


    private void setData() {
        //添加数据;
        shop_case.setText(""+meShopDetBean.getData().getCasesCount());
        shop_allp.setText(""+meShopDetBean.getData().getProductCount());
        shop_new.setText(""+meShopDetBean.getData().getNewCreate());
        shop_content.setText(meShopDetBean.getData().getNvc_Address());
        x.image().bind( shop_pic_imag,meShopDetBean.getData().getNvc_Banner(), ImageOptionsUtil.getOptions292_700_fixy());
//        x.image().bind( shop_image_circle,meShopDetBean.getData().getNvc_Logo(), ImageOptionsUtil.getcircle_fixy());
        x.image().loadDrawable(meShopDetBean.getData().getNvc_Logo(), ImageOptionsUtil.getcircle_fixy_50(), new Callback.CommonCallback<Drawable>() {
            @Override
            public void onSuccess(Drawable result) {
                if(result!=null) {
                    byte[] bytes = drawableToByte(result);
                    shop_image_circle.setImageBitmap(decodeSampledBitmapFromNet(bytes, imgWidth, imgHeight));
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });

        NumberOffans = meShopDetBean.getData().getBusinessMemberCount();
        shop_Fans_num.setText(""+NumberOffans);
        shop_name.setText(meShopDetBean.getData().getNvc_StoreName());
        isAttention=meShopDetBean.getData().isCollectionStare();
        if(!isLogin){//如果用户未登录，默认是没有关注，显示  +关注，
            isAttention=false;
        }

        if (isAttention){
            shop_attention_tv.setText("已关注");
        }else{
            shop_attention_tv.setText("+ 关注");
        }
    }

    //点击事件;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //点击关注;
            case R.id.shop_attention_tv:
                if (isLogin){
                    if(isCanClick){
                        if (isAttention){//关注
                            //取消关注
                            unsubscribe();
                            isAttention=false;
                        }else{
                            attention();
                            isAttention=true;
                        }
                        isCanClick=false;
                    }
                }else {
                    showLoginDialog();
                }
                break;
            //如果没有数据了
            case R.id.noNetLay:
                meInitData();
                getNetData(1);
                break;

            //点击图片跳转界面
            case R.id.shop_pic_imag:
                Intent intent = new Intent(this, HomeShopdetailQRActivity.class);
                intent.putExtra("BusinessID",BusinessID);
                intent.putExtra("nvc_num",getNvcNo);
                startActivity(intent);
                break;
            //点击全部商品
            case R.id.lay_shopdetail_all:
                if(meShopDetBean!=null) {
                    int allCount = meShopDetBean.getData().getProductCount();
                    int casesCount = meShopDetBean.getData().getCasesCount();
                    int newCount = meShopDetBean.getData().getNewCreate();
                    Intent intent2 = new Intent(this, HomeShopCaseActivity.class);
                    intent2.putExtra("index",1);
                    intent2.putExtra("allCount",allCount);
                    intent2.putExtra("casesCount",casesCount);
                    intent2.putExtra("newCount",newCount);
                    intent2.putExtra("BusinessID",BusinessID);
                    startActivity(intent2);
                }
                break;
            //点击案例商品
            case R.id.lay_shopdetail_case:
                if(meShopDetBean!=null) {
                    int allCount = meShopDetBean.getData().getProductCount();
                    int casesCount = meShopDetBean.getData().getCasesCount();
                    int newCount = meShopDetBean.getData().getNewCreate();
                    Intent intent2 = new Intent(this, HomeShopCaseActivity.class);
                    intent2.putExtra("index",2);
                    intent2.putExtra("allCount",allCount);
                    intent2.putExtra("casesCount",casesCount);
                    intent2.putExtra("newCount",newCount);
                    intent2.putExtra("BusinessID",BusinessID);
                    startActivity(intent2);
                }
                break;
            //点击新上架的商品
            case R.id.lay_shopdetail_new:
                if(meShopDetBean!=null) {
                    int allCount = meShopDetBean.getData().getProductCount();
                    int casesCount = meShopDetBean.getData().getCasesCount();
                    int newCount = meShopDetBean.getData().getNewCreate();
                    Intent intent2 = new Intent(this, HomeShopCaseActivity.class);
                    intent2.putExtra("index",3);
                    intent2.putExtra("allCount",allCount);
                    intent2.putExtra("casesCount",casesCount);
                    intent2.putExtra("newCount",newCount);
                    intent2.putExtra("BusinessID",BusinessID);
                    startActivity(intent2);
                }
                break;
            //返回键
            case R.id.lay_back:
                Intent intent1 = getIntent();
                intent1.putExtra("isAtten",isAttention);
                setResult(HomeStoreDetailsActivity.getAttenRes,intent1);
                finish();
            break;
            //打电话
            case R.id.shop_pw:
                if (mPopWindow!=null){
                    mPopWindow.dismiss();
                }
                //判断权限
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},REQUEST_CODE_ASK_CALL_PHONE);
                    return;
                }else{
                    showPopupWindow();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        isLogin= ((GlobalApplication)getApplication()).isLogin();
        user = DataWareHourse.getInstance().getmUser();
        if (user!=null){
            userBean = user.getData().get(0);
            memberID=userBean.getI_Id();
        }
        if (requestCode==REQUEST_LOGIN_CODE&&resultCode==LoginActivity.LOGIN_OK){
            if(isCanClick){
                if (isAttention){//关注
                    //取消关注
                    unsubscribe();
                    isAttention=false;
                }else{
                    attention();
                    isAttention=true;
                }
                isCanClick=false;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    public  void showLoginDialog() {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(this,   "亲，需要登录哦~", "去登录",  "取消", R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(ShopDetailsActivity.this, LoginActivity.class);
                startActivityForResult(intent,REQUEST_LOGIN_CODE);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    /**
     * 关注接口
     * POST WeddingMobileApi/post_BusinessMemberCreate?Token={Token}&MemberID={MemberID}&BusinessID={BusinessID}
     * +关注 关注店铺
     */
    private void  attention(){
        String url =  Url.POST_BUSINESSMEMBERCREATE+"&MemberID="+memberID+"&BusinessID="+BusinessID;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.POST_BUSINESSMEMBERCREATE);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }
    /**
     * POST WeddingMobileApi/post_CancelBusinessMember?Token={Token}&MemberID={MemberID}&BusinessID={BusinessID}
     * 取消关注
     */
    private  void  unsubscribe(){
        String url =  Url.POST_CANCELBUSINESSMEMBER + "&MemberID="+memberID+"&BusinessID="+BusinessID;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.POST_BUSINESSMEMBERCREATE);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK ) {
            Intent intent1 = getIntent();
            intent1.putExtra("isAtten",isAttention);
            setResult(HomeStoreDetailsActivity.getAttenRes,intent1);
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    //显示窗体
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_home_wedreg_phone, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, true);

        //设置各个控件的点击响应
        RelativeLayout mPhoneRaly = (RelativeLayout) contentView.findViewById(R.id.rlay_phonenum);
        RelativeLayout mCallRaly = (RelativeLayout) contentView.findViewById(R.id.rl_home_call);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_telephone_cancel);
        TextView mCallPhonelTv = (TextView) contentView.findViewById(R.id.tv_firstnum);
        TextView mCallTv = (TextView) contentView.findViewById(R.id.tv_home_call);
        mCallRaly.setVisibility(View.GONE);
        String nvc_telPhone = meShopDetBean.getData().getNvc_TelPhone();
        String nvc_mobilePhone =  meShopDetBean.getData().getNvc_MobilePhone();

        if(TextUtils.isEmpty(nvc_mobilePhone)) {
            mPhoneRaly.setVisibility(View.GONE);
        }else{
            mPhoneRaly.setVisibility(View.VISIBLE);
            mCallPhonelTv.setText(" "+ meShopDetBean.getData().getNvc_MobilePhone());

        }

        if(TextUtils.isEmpty(nvc_telPhone)) {
            mCallRaly.setVisibility(View.GONE);
        }else{
            mCallRaly.setVisibility(View.VISIBLE);
            mCallTv.setText("" + meShopDetBean.getData().getNvc_TelPhone());
        }

        if(nvc_telPhone.equals(nvc_mobilePhone)) {
            mPhoneRaly.setVisibility(View.GONE);
        }


        mCallRaly.setOnClickListener(new View.OnClickListener() {  // 点击电话按钮
            @Override
            public void onClick(View v) {
                String call = "" + meShopDetBean.getData().getNvc_TelPhone();
                Uri uri = Uri.parse("tel:" + call);
                Intent intent = new Intent(Intent.ACTION_DIAL,uri);
                startActivity(intent);
            }
        });

        mPhoneRaly.setOnClickListener(new View.OnClickListener() {  // 点击手机按钮
            @Override
            public void onClick(View v) {
                String phone = "" + meShopDetBean.getData().getNvc_MobilePhone();
                Uri uri = Uri.parse("tel:" + phone);
                Intent intent = new Intent(Intent.ACTION_DIAL,uri);
                startActivity(intent);
            }
        });
        mCancelTv.setOnClickListener(new View.OnClickListener() {   //点击取消按钮
            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        });

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();

                }
            }
        });

        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2));
        mPopWindow.setBackgroundDrawable(dw);
        mPopWindow.showAtLocation(mBackIv, Gravity.BOTTOM, 0, 0);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showPopupWindow();
                } else {
                    Toast.makeText(this, "请设置电话权限", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public  synchronized  byte[] drawableToByte(Drawable drawable) {

        if (drawable != null) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            int size = bitmap.getWidth() * bitmap.getHeight() * 4;
            // 创建一个字节数组输出流,流的大小为size
            ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
            // 设置位图的压缩格式，质量为100%，并放入字节数组输出流中
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            // 将字节数组输出流转化为字节数组byte[]
            byte[] imagedata = baos.toByteArray();
            return imagedata;
        }
        return null;
    }



    public static Bitmap decodeSampledBitmapFromNet(byte[] data, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeByteArray(data, 0, data.length, options);
    }



    public static synchronized int calculateInSampleSize(BitmapFactory.Options options,
                                                         int reqWidth, int reqHeight) {

        options.inJustDecodeBounds = true;
        final int height = options.outHeight;
        final int width = options.outWidth;

        int inSampleSize = 1;
        //方式一需要的参数
        int inSampleSize1 = 1;

        if (height > reqHeight || width > reqWidth) {

            //方式一
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while (((halfHeight / inSampleSize1) > reqHeight) && ((halfWidth / inSampleSize1) > reqWidth)) {
                SystemClock.sleep(2000);

                inSampleSize1 *= 2;
            }

        }
        return inSampleSize1;
    }


}
